﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace 进程通讯.客户端
{
    interface ISocketCLient
    {
        bool Connect(string ip, int prot);
        void Stop();
        void Send(byte[] data);
    }

    public class SocketClient : ISocketCLient
    {
        Socket Client;
        bool IsStop = false;
        public int ReceiveBufferSize { get; set; } = 1024;
        public event Action<byte[]> Receive;

        public bool Connect(string host, int prot)
        {
            try
            {
                Client = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
                Client.Connect(host, prot);
                Task.Run(ServerData);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return false;
        }

        private void ServerData()
        {
            try
            {
                while (!IsStop)
                {
                    if (Client == null) break;
                    byte[] buffer = new byte[ReceiveBufferSize];
                    int len = Client.Receive(buffer);
                    if (len <= 0) break;
                    byte[] data = buffer.Take(len).ToArray();
                    try
                    {
                        Receive?.Invoke(data);
                    }
                    catch
                    {
                    }
                }
            }
            catch (Exception)
            {
            }
        }

        public void Stop()
        {
            Client = null;
        }

        public void Send(byte[] data)
        {
            try
            {
                Client?.Send(data);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
